package com.LeetCode.why56;


import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

class Interval {
    int start;
    int end;

    Interval() {
        start = 0;
        end = 0;
    }

    Interval(int s, int e) {
        start = s;
        end = e;
    }
}

public class MergeIntervals {

    public static List<Interval> merge(List<Interval> intervals) {
        int len = intervals.size();
        if (len == 0) return intervals;
        //排序
        intervals.sort(new Comparator<Interval>() {
            @Override
            public int compare(Interval o1, Interval o2) {
                if (o1.start > o2.start)
                    return 1;
                else if (o1.start < o2.start)
                    return -1;
                else return 0;
            }
        });


        for (int i = 0; i + 1 < intervals.size(); i++) {
            Interval current = intervals.get(i);
            Interval next = intervals.get(i + 1);
            if (current.end >= next.start) {
                current.end = Math.max(current.end, next.end);
                intervals.remove(i + 1);
                i--;
            }
        }
        return intervals;
    }

    public static void main(String[] args) {
        List<Interval> test = new ArrayList<>();
        test.add(new Interval(2, 6));
        test.add(new Interval(1, 3));
        test.add(new Interval(2, 6));
        test.add(new Interval(8, 10));
        test.add(new Interval(15, 18));

        List<Interval> result = merge(test);
        Iterator<Interval> it = result.listIterator();
        while (it.hasNext()) {
            Interval temp = it.next();
            System.out.println("[" + temp.start + "," + temp.end + "]");
        }

    }
}
